package com.chenlonghai.sbmybatis.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.chenlonghai.sbmybatis.entity.AppModelTest;


import net.sf.json.JSON;

@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
//请求处理之后执行
	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object obj, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		 System.out.println("afterCompletion");
	}
//视图渲染之后执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model)
			throws Exception {
		// TODO Auto-generated method stub
		 System.out.println("postHandle");
	}
//请求处理调用之前，只有返回true才会执行请求
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		// TODO Auto-generated method stub 前端放在session
//		HttpSession session = request.getSession();
//	    String sysUserId = (String) session.getAttribute("sysUserId");
//	     if(sysUserId!=null && Integer.getInteger(sysUserId) != 0){
//		  return true;
//		  
//	  }	
		//打印所有的值
//		System.out.println("request-->" +request.getParameterNames());
//		Enumeration paramNames = request.getParameterNames();
//		while(paramNames.hasMoreElements()){
//		    String name=(String)paramNames.nextElement();
//		    String value=request.getParameter(name);
//		    System.out.println(name + "=" + value);
//		}
		 Object sysUserId =  request.getParameter("sysUserId");
//		 if(sysUserId !=null){
//			  return true;  
//		  }
		 Map<String, Object>map =  new HashMap<String, Object>();
        AppModelTest<String> appmodel = new AppModelTest<String>("未法登录", map);
        
        returnJson(response, net.sf.json.JSONObject.fromObject(appmodel.getResultMap()).toString());
		return false;
	}

	private void returnJson(HttpServletResponse response, String json) throws Exception{
	    PrintWriter writer = null;
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html; charset=utf-8");
	    try {
	        writer = response.getWriter();
	        writer.print(json);
	        System.out.println(json);

	    } catch (IOException e) {
	     System.out.println(e.getMessage());
	    } finally {
	        if (writer != null)
	            writer.close();
	    }
	}
	
}

